<template>
  <view class="container">
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-header">
        <text class="filter-title">筛选条件</text>
        <u-icon v-if="showFilter" name="arrow-up" size="24" @click="toggleFilter" />
        <u-icon v-else name="arrow-down" size="24" @click="toggleFilter" />
      </view>

      <view v-show="showFilter" class="filter-content">
        <view class="filter-item">
          <text class="filter-label">时间范围</text>
          <view class="filter-options">
            <u-tag
              v-for="(item, index) in timeFilters"
              :key="index"
              :text="item.label"
              :type="selectedTimeFilter === item.value ? 'primary' : 'info'"
              shape="circle"
              @click="selectTimeFilter(item.value)"
              class="filter-tag"
            />
          </view>
        </view>

        <view class="filter-item">
          <text class="filter-label">自定义时间</text>
          <view class="date-picker-container">
            <view class="date-picker" @click="openStartDatePicker">
              <text>{{ startDate || '开始日期' }}</text>
              <u-icon name="calendar" size="20" />
            </view>
            <text class="date-separator">至</text>
            <view class="date-picker" @click="openEndDatePicker">
              <text>{{ endDate || '结束日期' }}</text>
              <u-icon name="calendar" size="20" />
            </view>
          </view>
        </view>

        <view class="filter-actions">
          <u-button type="primary" size="small" @click="applyFilters" class="filter-button"> 应用筛选 </u-button>
          <u-button type="default" size="small" @click="resetFilters" class="filter-button reset-button"> 重置 </u-button>
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-value">{{ totalOrders }}</text>
        <text class="stat-label">总订单数</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ todayOrders }}</text>
        <text class="stat-label">今日核销</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="scroll-container" scroll-y="true" @scrolltolower="reachBottom">
      <view v-for="(item, index) in listData" :key="index" class="order-item" @click="toDetail(item)">
        <image class="order-image" :src="getImageUrl(item.ebMerActivityIcon)" mode="aspectFill"></image>

        <view class="order-info">
          <view class="order-title">{{ item.ebMerActivityTicketName }}</view>
          <view class="order-subtitle">{{ item.ebMerActivityName }}</view>

          <view class="order-details">
            <view class="order-amount">
              <text class="amount-label">核销金额：</text>
              <text class="amount-value">¥{{ item.payPrice }}</text>
            </view>
            <view class="order-time">核销时间：{{ formatDateTime(item.verificationTime) }}</view>
          </view>

          <view class="order-status">
            <u-tag text="已核销" type="success" size="mini" shape="circle" />
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading">
        <u-loading-icon mode="circle" size="24" />
        <text class="loading-text">加载中...</text>
      </view>

      <view v-if="!goodScroll && !loading && listData.length > 0" class="no-more">
        <u-icon name="file-text" size="24" />
        <text class="no-more-text">没有更多了</text>
      </view>

      <view v-if="!loading && listData.length === 0" class="empty-state">
        <u-empty mode="list" text="暂无核销订单" icon="http://36.139.124.9:9000/community/img/empty.png"> </u-empty>
      </view>
    </scroll-view>

    <!-- 日期选择器 -->
    <u-datetime-picker :show="showStartDatePicker" mode="date" v-model="startDateTimestamp" @confirm="confirmStartDate" @cancel="showStartDatePicker = false" />

    <u-datetime-picker :show="showEndDatePicker" mode="date" v-model="endDateTimestamp" @confirm="confirmEndDate" @cancel="showEndDatePicker = false" />
  </view>
</template>

<script>
import { reconciledList } from '../../utils/merorder/mer';
import { IMG_URL } from '../../config/index.js';

export default {
  data() {
    return {
      listData: [],
      loading: false,
      goodScroll: true,
      imgurl: IMG_URL,
      totalOrders: 0,
      todayOrders: 0,

      // 筛选相关
      showFilter: false,
      timeFilters: [
        { label: '全部', value: 'all' },
        { label: '今天', value: 'today' },
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' }
      ],
      selectedTimeFilter: 'all',
      startDate: '',
      endDate: '',
      startDateTimestamp: Date.now(),
      endDateTimestamp: Date.now(),
      showStartDatePicker: false,
      showEndDatePicker: false,

      // 分页数据
      params: {
        page: 1,
        limit: 10
      }
    };
  },

  onLoad() {
    this.initDateFilters();
    this.fetchData();
    this.fetchStats();
  },

  methods: {
    // 初始化日期筛选器
    initDateFilters() {
      const now = new Date();
      this.startDate = this.formatDate(now);
      this.endDate = this.formatDate(now);
      this.startDateTimestamp = now.getTime();
      this.endDateTimestamp = now.getTime();
    },

    // 切换筛选面板显示
    toggleFilter() {
      this.showFilter = !this.showFilter;
    },

    // 选择时间筛选条件
    selectTimeFilter(value) {
      this.selectedTimeFilter = value;

      // 根据选择设置日期范围
      const now = new Date();
      switch (value) {
        case 'today':
          this.startDate = this.formatDate(now);
          this.endDate = this.formatDate(now);
          break;
        case 'week':
          const weekStart = new Date(now);
          weekStart.setDate(now.getDate() - now.getDay() + 1); // 本周一
          const weekEnd = new Date(weekStart);
          weekEnd.setDate(weekStart.getDate() + 6); // 本周日
          this.startDate = this.formatDate(weekStart);
          this.endDate = this.formatDate(weekEnd);
          break;
        case 'month':
          const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
          const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
          this.startDate = this.formatDate(monthStart);
          this.endDate = this.formatDate(monthEnd);
          break;
        default:
          // 全部时不清空日期，保持自定义日期
          break;
      }
    },

    // 打开开始日期选择器
    openStartDatePicker() {
      this.showStartDatePicker = true;
    },

    // 打开结束日期选择器
    openEndDatePicker() {
      this.showEndDatePicker = true;
    },

    // 确认开始日期
    confirmStartDate({ value }) {
      this.startDate = this.formatDate(new Date(value));
      this.startDateTimestamp = value;
      this.showStartDatePicker = false;
    },

    // 确认结束日期
    confirmEndDate({ value }) {
      this.endDate = this.formatDate(new Date(value));
      this.endDateTimestamp = value;
      this.showEndDatePicker = false;
    },

    // 应用筛选条件
    applyFilters() {
      this.params.page = 1;
      this.listData = [];
      this.fetchData();
    },

    // 重置筛选条件
    resetFilters() {
      this.selectedTimeFilter = 'all';
      this.initDateFilters();
      this.params.page = 1;
      this.listData = [];
      this.fetchData();
    },

    // 获取数据
    fetchData() {
      this.loading = true;
      if (!this.goodScroll && this.params.page > 1) {
        this.loading = false;
        return;
      }

      const params = {
        ...this.params,
        orderType: 2,
        status: 2,
        verificationMerId: uni.getStorageSync('merId')
      };

      // 添加日期筛选条件
      if (this.startDate) {
        params.startDate = this.startDate;
      }
      if (this.endDate) {
        params.endDate = this.endDate;
      }

      reconciledList(params)
        .then((res) => {
          let lists = [];
          if (res.data && res.data.list) {
            lists = res.data.list;
          }

          this.loading = false;
          this.goodScroll = lists.length >= this.params.limit;
          this.params.page++;
          this.listData = this.listData.concat(lists);
        })
        .catch((error) => {
          this.loading = false;
          console.error('获取数据失败:', error);
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        });
    },

    // 获取统计数据
    fetchStats() {
      // 这里可以调用接口获取统计数据
      // 暂时使用模拟数据
      this.totalOrders = 128;
      this.todayOrders = 5;
    },

    // 滚动到底部加载更多
    reachBottom() {
      this.fetchData();
    },

    // 跳转到核销详情页
    toDetail(data) {
      const ticketCode = data.ebMerActivityTicketRecordList[0].ticketCode;
      uni.navigateTo({
        url: '/pages_sh/orderCode/redempt?ticketCode=' + ticketCode
      });
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      return dateTime.replace('T', ' ').substring(0, 16);
    },

    // 获取图片完整URL
    getImageUrl(icon) {
      if (!icon) return 'http://36.139.124.9:9000/community/img/default.png';
      if (icon.includes('http')) return icon;
      return this.imgurl + icon;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.filter-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .filter-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .filter-content {
    padding-top: 20rpx;

    .filter-item {
      margin-bottom: 30rpx;

      .filter-label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
      }

      .filter-options {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;

        .filter-tag {
          margin-bottom: 10rpx;
        }
      }

      .date-picker-container {
        display: flex;
        align-items: center;

        .date-picker {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          background-color: #f8f8f8;
          border-radius: 10rpx;
          padding: 20rpx;
          font-size: 28rpx;
          color: #333;
        }

        .date-separator {
          margin: 0 20rpx;
          color: #999;
        }
      }
    }

    .filter-actions {
      display: flex;
      justify-content: flex-end;
      gap: 20rpx;

      .filter-button {
        width: 180rpx;
      }

      .reset-button {
        background-color: #f0f0f0;
        color: #666;
      }
    }
  }
}

.stats-section {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  .stat-item {
    flex: 1;
    text-align: center;

    .stat-value {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }

    .stat-label {
      font-size: 24rpx;
      color: #999;
    }
  }

  .stat-item:not(:last-child) {
    border-right: 1rpx solid #f0f0f0;
  }
}

.scroll-container {
  height: calc(100vh - 400rpx);
}

.order-item {
  display: flex;
  padding: 24rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
}

.order-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.order-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.order-subtitle {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.order-details {
  .order-amount {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    .amount-label {
      font-size: 24rpx;
      color: #999;
    }

    .amount-value {
      font-size: 28rpx;
      font-weight: bold;
      color: #ff6600;
    }
  }

  .order-time {
    font-size: 24rpx;
    color: #999;
  }
}

.order-status {
  align-self: flex-end;
}

.loading,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;

  .loading-text,
  .no-more-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #999;
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

@media (max-width: 768px) {
  .container {
    padding: 10rpx;
  }

  .filter-section,
  .stats-section,
  .order-item {
    border-radius: 12rpx;
  }

  .order-image {
    width: 120rpx;
    height: 120rpx;
  }
}
</style>
